package com.yu.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.shortlink.admin.common.constant.RedisCacheConstant;
import com.yu.shortlink.admin.common.convention.exception.ClientException;
import com.yu.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.yu.shortlink.admin.dao.entity.UserDO;
import com.yu.shortlink.admin.dao.mapper.UserMapper;
import com.yu.shortlink.admin.dto.req.UserLoginReqDTO;
import com.yu.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.yu.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.yu.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.yu.shortlink.admin.dto.resp.UserRespDTO;
import com.yu.shortlink.admin.service.GroupService;
import com.yu.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * (TUser)表服务实现类
 *
 * @author yushiwang

 * @since 2024-03-26 23:05:40
 */
@Service("UserService")
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final GroupService groupService;

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate redisTemplate;
    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUsername,username);
        UserDO userDO = this.getOne(queryWrapper);
        if (Objects.isNull(userDO)){
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDTO userRespDTO = BeanUtil.toBean(userDO, UserRespDTO.class);
        return userRespDTO;
    }

    @Override
    public Boolean hasUserName(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO userRegisterReqDTO) {
        if (hasUserName(userRegisterReqDTO.getUsername())){
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY +userRegisterReqDTO.getUsername());
        try {
            if (lock.tryLock()){
                try {
                    int insert = baseMapper.insert(BeanUtil.toBean(userRegisterReqDTO, UserDO.class));
                    if (insert < 1){
                        throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
                    }
                } catch (DuplicateKeyException e) {
                    throw new ClientException(UserErrorCodeEnum.USER_EXIST);
                }
                userRegisterCachePenetrationBloomFilter.add(userRegisterReqDTO.getUsername());
                groupService.saveGroup(userRegisterReqDTO.getUsername(),"默认分组");
                return;
            }
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        } finally {
            lock.unlock();
        }

    }

    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        // TODO 验证当前用户名是否为当前用户
        LambdaUpdateWrapper<UserDO> eq = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, userUpdateReqDTO.getUsername());
        baseMapper.update(BeanUtil.toBean(userUpdateReqDTO, UserDO.class),eq);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaQueryWrapper<UserDO> eq = new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDO::getPassword, userLoginReqDTO.getPassword())
                .eq(UserDO::getDelFlag, 0);
            List<UserDO> userDOS = baseMapper.selectList(eq);
        UserDO userDO = baseMapper.selectOne(eq);
        if (Objects.isNull(userDO)){
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        if (Boolean.TRUE.equals(redisTemplate.hasKey("login_" + userLoginReqDTO.getUsername()))){
            throw new ClientException("用户已登录");
        }
        /**
         * Hash
         * key:login_用户名
         * Value:
         *  key:token
         *  value:JSON 字符串(用户信息)
         */
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForHash().put("login_"+userLoginReqDTO.getUsername(),token, JSON.toJSONString(userDO));
        redisTemplate.expire("login_"+userLoginReqDTO.getUsername(),30L, TimeUnit.DAYS);
        return new UserLoginRespDTO(token);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return Objects.nonNull(redisTemplate.opsForHash().get("login_"+username,token));
    }

    @Override
    public void logout(String username, String token) {
        if (!checkLogin(username, token)){
            throw new ClientException("用户未登录");
        }
        redisTemplate.delete("login_"+username);
    }
}

